import { type AxiosResponse } from 'axios'
import { isPlainObject } from 'lodash'
import { type CommonResponseDataType } from 'types/common-types/response.ts'

/**
 * 判断请求是否成功（后台约定，code为8位数字，后六位表示状态，前两位表示业务代号
 * @param {number} code 后台返回的状态码
 * @returns {boolean} true表示请求成功
 */
function isRequestSucess(code: number): boolean {
  const strCode = String(code)
  const status = Number.parseInt(strCode.substring(2), 10)
  return status === 0
}

/**
 * 拦截器---errCode
 * @template T
 * @param {AxiosResponse<T>} response 响应数据
 * @returns {AxiosResponse<T>} 响应数据
 */
function ErrorCodeInterceptor<T = any>(
  response: AxiosResponse<CommonResponseDataType<T>>,
): AxiosResponse<CommonResponseDataType<T>> | Promise<AxiosResponse<CommonResponseDataType<T>>> {
  const { status } = response // Http 状态码
  const responseData: CommonResponseDataType<T> = response.data
  if (isPlainObject(responseData)) {
    // data是object对象的情况
    const errCode: number = responseData.code || responseData.respCode

    if (status == 200 && isRequestSucess(errCode)) {
      // 框架返回/系统定义
      // 成功
      return response
    }
    if (status == 200 && errCode === 14000003) {
    }
  }

  if (status == 200) {
    return response
  }
  return Promise.reject(new Error('请求失败(1)'))
}

export { ErrorCodeInterceptor }
